<?php
/*
 * Author  : top-songshijie
 * Email   : 997031758@qq.com
 * DateTime: 2023/04/12 11:37
 */

namespace SSJ\LaravelHelper\Console\Schedule;

use Illuminate\Console\Command;
use SSJ\LaravelHelper\Support\Log;
use Illuminate\Support\Facades\File;

class BackupDatabase extends Command
{
    protected $signature = 'lh:schedule:backup-database';

    protected $description = '备份数据库';

    public function handle()
    {
        try {
            $dir = storage_path('app/database/' . date('Y-m-d').'/');
            File::isDirectory($dir) or File::makeDirectory($dir, 0777, true, true);

            $file_name = date('His') . '.sql';
            system(sprintf(
                'mysqldump -h%s -p%s -u%s -p%s %s > %s',
                config('database.connections.mysql.host'),
                config('database.connections.mysql.port'),
                config('database.connections.mysql.username'),
                config('database.connections.mysql.password'),
                config('database.connections.mysql.database'),
                $dir . $file_name
            ));

        } catch (\Throwable $throwable) {
            Log::exception($throwable);
            return true;
        }

        lh_info('备份数据库', ['备份文件' => $file_name]);

        return true;
    }
}
